package cn.com.xy.sms.sdk.db.entity;

import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;

import android.content.ContentValues;
import cn.com.xy.sms.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.DBManager;
import cn.com.xy.sms.sdk.db.XyCursor;
import cn.com.xy.sms.sdk.db.base.BaseManager;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.service.msgurlservice.MsgUrlService;
import cn.com.xy.sms.sdk.util.StringUtils;

public class MsgUrlManager {

    public static final String TABLE_NAME = "tb_msg_url";
    public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME;

    // validStatus:-1黑名单类型的域名、1非域名库类型的域名、2白名单类型的域名
    public static final int NOT_CHECK = 0;
    public static final int BLACK_LIST = -1;
    public static final int NOT_YUMING = 1;
    public static final int WHITE_LIST = 2;
    public static final String DIVDER = "_ARR_";

    public static final String URL = "url";
    public static final String CHECK_TIME = "check_time";
    public static final String CHECK_STATU = "check_statu";
    public static final String THIRD_CHECK_STATU = "third_check_statu";

    public static String getCreateTableSql() {
        return "create table  if not exists " + TABLE_NAME + " ( " + " id INTEGER PRIMARY KEY," + " url TEXT,"
                + " check_time integer default 0," + " check_statu integer default 0,"
                + " third_check_statu integer default 0" + ")";
    }

    public static JSONArray queryCheckTimeExpireData() {
        JSONArray jsonArray = new JSONArray();
        long cyc = DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_URL_VAILD_CYCLE, Constant.month);
        long startTime = System.currentTimeMillis() - cyc;
        XyCursor cur = null;
        try {
            cur = DBManager.query(TABLE_NAME, new String[] { URL }, CHECK_TIME + " < ? ",
                    new String[] { startTime + "" });
            if (cur != null && cur.getCount() > 0) {
                int urlIndex = cur.getColumnIndex(URL);
                while (cur.moveToNext()) {
                    JSONObject json = new JSONObject();
                    json.put("url", cur.getString(urlIndex));
                    jsonArray.put(json);
                }

            }
        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "queryCheckTimeExpireData: " + e.getMessage(), e);

        } finally {
            XyCursor.closeCursor(cur, true);
        }
        return jsonArray;
    }

    public static void saveOrUpdate(JSONArray jsonArray) {
        if (jsonArray == null || jsonArray.length() <= 0)
            return;
        for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject json = jsonArray.optJSONObject(i);
            String url = json.optString("originURL");
            int statu = json.optInt("validStatus");
            saveOrUpdate(url, statu);
        }
    }

    public static void saveOrUpdate(String urls) {
        if (StringUtils.isNull(urls))
            return;
        try {
            String[] arr = urls.split(DIVDER);
            if (arr == null)
                return;
            for (int i = 0; i < arr.length; i++) {
                saveOrUpdate(arr[i], NOT_CHECK);
            }
        } catch (Throwable e) {
            // TODO: handle exception
        }

    }

    /**
     * 更新第三方验证的状态
     * 
     * @param url
     * @param thirdStatu
     * @return
     */
    public static long saveOrUpdateThirdStatu(String url, int thirdStatu) {
        long result = -1;
        ContentValues values = null;
        try {
            values = BaseManager.getContentValues(null, URL, url, THIRD_CHECK_STATU, thirdStatu + "", CHECK_TIME,
                    String.valueOf(System.currentTimeMillis()));
            int rows = -1;

            rows = DBManager.update(TABLE_NAME, values, URL + " = ? ", new String[] { url });
            if (rows <= 0) {
                result = DBManager.insert(TABLE_NAME, values);
            } else {
                result = 0;
            }

        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "saveOrUpdateThirdStatu: ", e);
            /* SDK-550 hewengao 20160719 start */
        } finally {
        }
        return result;
    }

    public static long saveOrUpdate(String url, int statu) {
        long result = -1;
        ContentValues values = null;
        try {
            values = BaseManager.getContentValues(null, URL, url, CHECK_STATU, statu + "", CHECK_TIME,
                    String.valueOf(System.currentTimeMillis()));
            int rows = -1;
            if (statu == NOT_CHECK) {
                rows = DBManager.update(TABLE_NAME, values, URL + " = ? and " + CHECK_STATU + " = ?", new String[] {
                        url, NOT_CHECK + "" });
                if (rows <= 0) {
                    result = DBManager.insert(TABLE_NAME, values);
                } else {
                    result = 0;
                }
            } else {
                rows = DBManager.update(TABLE_NAME, values, URL + " = ? ", new String[] { url });
                if (rows <= 0) {
                    result = DBManager.insert(TABLE_NAME, values);
                } else {
                    result = 0;
                }
            }
        } catch (Throwable e) {
            // e.printStackTrace();
            /* SDK-550 hewengao 20160719 start */
            LogManager.w(Constant.TAG, "saveOrUpdate: ", e);
            /* SDK-550 hewengao 20160719 end */
        } finally {
        }
        return result;
    }

	    public static int queryStatuByUrl(String url,boolean isThird) {
	        XyCursor cursor = null;	      
	        try {	
	        	String queryCol = "";	        	
	        	if(isThird){
	        		queryCol = THIRD_CHECK_STATU;
	        	}else{
	        		queryCol = CHECK_STATU;
	        	}
	            cursor = DBManager.query(
	                    TABLE_NAME, new String[] {queryCol},URL + " = ? ", new String[] { url });
	            if (cursor != null && cursor.moveToNext()) {
	                return cursor.getInt(cursor.getColumnIndex(queryCol));
	            }
	            else{
	            	return 0;
	            }
	        } catch (Throwable e) {
//	            e.printStackTrace();
	            /*SDK-550 hewengao 20160719 start*/
	            LogManager.e(Constant.TAG, "queryStatuByUrl: ", e);
	            /*SDK-550 hewengao 20160719 end*/
	        } finally {
	            XyCursor.closeCursor(cursor, true);
	        }
	        return 0;
	    
	    }
	
	public static HashMap<String, Object> queryStatuByUrls(String[] url, boolean isThird) {
		HashMap<String, Object> map = new HashMap<String, Object>();
		boolean hasNotCheck = false;
		int result = Integer.MAX_VALUE;
		int min = Integer.MAX_VALUE;
		for (int i = 0; i < url.length; i++) {
			result = queryStatuByUrl(url[i], isThird);
			if (result == NOT_CHECK) {
				hasNotCheck = true;
			}
			if (result <= min) {
				min = result;
			}
			if (min == MsgUrlService.RESULT_BLACK_LIST) {
				break;
			}
		}
		map.put("statu", min);
		if (hasNotCheck) {
			map.put("hasNotCheck", true);
		}
		return map;
	}
	    
	 
}
